package com.ybzl.system.controller.system;

import com.ybzl.common.annotation.Log;
import com.ybzl.common.constant.CacheConstants;
import com.ybzl.common.core.controller.BaseController;
import com.ybzl.common.core.domain.Result;
import com.ybzl.common.core.domain.entity.SysDept;
import com.ybzl.common.core.domain.entity.SysRole;
import com.ybzl.common.core.domain.entity.SysUser;
import com.ybzl.common.core.page.PageData;
import com.ybzl.common.core.redis.RedisCache;
import com.ybzl.common.enums.BusinessType;
import com.ybzl.common.utils.SecurityUtils;
import com.ybzl.common.utils.StringUtils;
import com.ybzl.common.utils.poi.ExcelUtil;
import com.ybzl.common.utils.sign.Md5Utils;
import com.ybzl.system.domain.MytemEntity;
import com.ybzl.system.domain.vo.MytemaVo;
import com.ybzl.system.service.ISysDeptService;
import com.ybzl.system.service.ISysPostService;
import com.ybzl.system.service.ISysRoleService;
import com.ybzl.system.service.ISysUserService;
import com.ybzl.system.web.service.TokenService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author dtf
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public PageData list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public Result importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        // 系统自建用户
        //userList.stream().forEach(user -> user.setSource("0"));
        String operName = getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public Result getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        Result ajax = Result.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(Result.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public Result add(@Validated @RequestBody SysUser user) {
        String regex = "^[a-zA-Z]+$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(user.getNickName());
        /*if (matcher.matches()) {
            return error("姓名不允许出现字母");
        }*/
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public Result edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        userService.updateUser(user);
        return Result.success();
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public Result remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public Result resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public Result changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());


        // todo 240831：同步删除缓存中的用户信息
        SysUser entity = userService.selectUserById(user.getUserId());
        String tokenPc = CacheConstants.LOGIN_TOKEN_KEY + "pc:" + Md5Utils.hash(entity.getUserId() + "@" + entity.getUserName());
        String tokenApp = CacheConstants.LOGIN_TOKEN_KEY + "app:" + Md5Utils.hash(entity.getUserId() + "@" + entity.getUserName());
        System.out.println(tokenPc);
        System.out.println(tokenApp);
        redisCache.deleteObject(tokenApp);
        redisCache.deleteObject(tokenPc);

        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public Result authRole(@PathVariable("userId") Long userId) {
        Result ajax = Result.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public Result insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    public Result deptTree(SysDept dept) {
        return success(deptService.selectDeptTreeList(dept));
    }


    /***
     * 查询我的团队信息
     * @return
     */
    @GetMapping("/myteams")
    public Result myteams() {




        // 只处理管理员账号
        if (SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            Map<String, Object> rtnData = new HashMap<>();

            // 1. 查询以董事起始
            SysUser queryDongshi = new SysUser();
            queryDongshi.setCtype("董事");
            queryDongshi.setParentName("admin");
            List<Map<String, Object>> dongshis = userService.getListById(queryDongshi);
            rtnData.put("dongshis", dongshis);
            rtnData.put("dongshisNums", dongshis.size());

            for (Map<String, Object> dongshi : dongshis) {

                Integer dsgfsNum = 0;
                Integer zsgfsNum = 0;

                // 1.1 董事下的官方
                SysUser queryDsgf = new SysUser();
                queryDsgf.setCtype("官方");
                queryDsgf.setParentName(String.valueOf(dongshi.get("userName")));
                List<Map<String, Object>> dsgf = userService.getListById(queryDsgf);
                dongshi.put("dsgfs", dsgf);
                dsgfsNum+=dsgf.size();

                for (Map<String, Object> guanfang : dsgf) {
                    // 1.1.1 董事下的官方下的创业
                    SysUser queryDsgfcy = new SysUser();
                    queryDsgfcy.setCtype("创业");
                    queryDsgfcy.setParentName(String.valueOf(guanfang.get("userName")));
                    List<Map<String, Object>> dsgfcys = userService.getListById(queryDsgfcy);
                    guanfang.put("dsgfcys", dsgfcys);
                    guanfang.put("dsgfcysNum", dsgfcys.size());
                    dsgfsNum+=dsgfcys.size();
                }


                // 1.2 董事下的创业
                SysUser queryDscy = new SysUser();
                queryDscy.setCtype("创业");
                queryDscy.setParentName(String.valueOf(dongshi.get("userName")));
                List<Map<String, Object>> dscys = userService.getListById(queryDscy);
                dongshi.put("dscys", dscys);
                dongshi.put("dscysNum", dscys.size());

                dsgfsNum +=  dscys.size();
                dongshi.put("dsgfsNum", dsgfsNum);

            }

            // 2. 查询以官方起始
            SysUser querygf = new SysUser();
            querygf.setCtype("官方");
            querygf.setParentName("admin");
            List<Map<String, Object>> zsgf = userService.getListById(querygf);
            rtnData.put("zsgfs", zsgf);
            rtnData.put("zsgfsNum", zsgf.size());

            for (Map<String, Object> item : zsgf) {
                SysUser zsgfcyQuery = new SysUser();
                zsgfcyQuery.setCtype("创业");
                zsgfcyQuery.setParentName(String.valueOf(item.get("userName")));
                List<Map<String, Object>> zsgfcy = userService.getListById(zsgfcyQuery);
                item.put("zsgfcys", zsgfcy);
                item.put("zsgfcysNum", zsgfcy.size());
            }


            // 3. 查询以创业起始
            SysUser zscyQu = new SysUser();
            zscyQu.setCtype("创业");
            zscyQu.setParentName("admin");
            List<Map<String, Object>> zscy = userService.getListById(zscyQu);
            rtnData.put("zscys", zscy);
            rtnData.put("zscysNum", zscy.size());

            rtnData.put("count", userService.userCount());

            return success(rtnData);
        } else {
            List<MytemEntity> guanfangs = userService.getMydownGuanfang(SecurityUtils.getUsername());
            List<MytemEntity> chuangyes = userService.getMydownChuangye(SecurityUtils.getUsername());

            // 1. 我的下级
            MytemaVo mytemaVo = new MytemaVo();
            mytemaVo.setGuanfangs(guanfangs);
            mytemaVo.setChuangyes(chuangyes);
            mytemaVo.setChuangyeNum(chuangyes.size());
            mytemaVo.setGuanfangNum(guanfangs.size());

            int guanfangExts = 0;
            if (!ObjectUtils.isEmpty(guanfangs)) {
                for (MytemEntity entity : guanfangs) {
                    List<MytemEntity> guanfangExt = userService.getMydownChuangye(entity.getUserName());
                    entity.setCyext(guanfangExt);
                    entity.setCyextNum(guanfangExt.size());
                    guanfangExts += guanfangExt.size();
                }
                //mytemaVo.setGuanfangNum(guanfangs.size()+nums);
            }
            // 创业已经是最底层了，无需处理

            // 2. 我的推荐人
            SysUser user1 = userService.selectUserByUserName(SecurityUtils.getUsername());
            SysUser user2 = userService.selectUserByUserName(user1.getParentName());

            if (!ObjectUtils.isEmpty(user2)) {
                mytemaVo.setParentName(user2.getUserName());
                mytemaVo.setParentNickName(user2.getNickName());
            } else {
                mytemaVo.setParentName("无");
                mytemaVo.setParentNickName("无");
            }

            mytemaVo.setCounts(chuangyes.size() + guanfangs.size() + guanfangExts);
            return success(mytemaVo);
        }
    }
}
